<template>
  <div class="app-container">
    <el-card>
      <!-- 顶部工单类型选择 -->
      <div class="header">
        <el-input v-model="queryParams.userName" style="width: 400px;" placeholder="搜索名称" clearable @clear="handleSearch">
            <template #append>
              <el-button icon="Search" @click="handleWorkOrderTypeChange" />
            </template>
          </el-input>
      </div>
    </el-card>
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog" icon="Plus">新增权限</el-button>
      <!-- <el-button type="primary" @click="showBatchDialog">批量设置</el-button> -->
      <!-- 权限配置表格 -->
      <el-table :data="permissionList" border class="permission-table mt-2" v-loading="loading"
        :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userName" label="用户名称" align="center" />
        <el-table-column prop="userType" label="用户类型" align="center">
          <template #default="{ row }">
            <el-tag>
              {{ getName(userTypeOptions, row.userType, 'dictValue', 'dictLabel') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="查看" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.viewPermission" :true-label="1" :false-label="0" />
          </template>
        </el-table-column>
        <el-table-column label="创建" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.createPermission" :true-label="1" :false-label="0" />
          </template>
        </el-table-column>
        <el-table-column label="编辑" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.editPermission" :true-label="1" :false-label="0" />
          </template>
        </el-table-column>
        <el-table-column label="删除" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.deletePermission" :true-label="1" :false-label="0" />
          </template>
        </el-table-column>
        <el-table-column label="指派" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.assignPermission" :true-label="1" :false-label="0" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" @click="handleSave(row)">保存</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="currentPermission" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="工单类型" prop="workOrderType">
          <el-select v-model="currentPermission.workOrderType" placeholder="请选择工单类型" style="width: 100%">
            <el-option v-for="item in workOrderTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="currentPermission.userType" placeholder="请选择用户类型" style="width: 100%"
            @change="handleUserTypeSelect">
            <el-option v-for="item in userTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="userId">
          <el-select v-model="currentPermission.userId" placeholder="请选择用户" style="width: 100%" filterable>
            <el-option v-for="item in userListOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="查看权限">
          <el-switch v-model="currentPermission.viewPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="创建权限">
          <el-switch v-model="currentPermission.createPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="编辑权限">
          <el-switch v-model="currentPermission.editPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="删除权限">
          <el-switch v-model="currentPermission.deletePermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="指派权限">
          <el-switch v-model="currentPermission.assignPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量设置对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量设置权限" width="50%" :close-on-click-modal="false">
      <el-form :model="batchForm" label-width="120px">
        <el-form-item label="查看权限">
          <el-switch v-model="batchForm.viewPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="创建权限">
          <el-switch v-model="batchForm.createPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="编辑权限">
          <el-switch v-model="batchForm.editPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="删除权限">
          <el-switch v-model="batchForm.deletePermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="指派权限">
          <el-switch v-model="batchForm.assignPermission" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchSet">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getWorkOrderTypeList,
  getUserTypeList,
  getUserList,
  getWorkOrderPermissionList,
  addWorkOrderPermission,
  updateWorkOrderPermission,
  batchSetWorkOrderPermission,
  deleteWorkOrderPermission
} from '@/api/prod_operate/sys_setting/work_order/work_auth'

// 加载状态
const loading = ref(false)

// 下拉选项数据
const workOrderTypeOptions = ref([])
const userTypeOptions = ref([])
const userListOptions = ref([])
// 权限列表数据
const permissionList = ref([])

const multipleSelection = ref('');

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  workOrderType: '',
  userType: '',
  userName: ''
})

// 当前编辑的权限
const currentPermission = reactive({
  permissionId: '',
  workOrderType: '',
  userType: '',
  userId: '',
  userName: '',
  viewPermission: 0,
  createPermission: 0,
  editPermission: 0,
  deletePermission: 0,
  assignPermission: 0
})

// 批量设置表单
const batchForm = reactive({
  workOrderType: '',
  userType: '',
  viewPermission: 0,
  createPermission: 0,
  editPermission: 0,
  deletePermission: 0,
  assignPermission: 0
})

// 对话框控制
const editDialogVisible = ref(false)
const editDialogTitle = ref('新增权限')
const batchDialogVisible = ref(false)
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  workOrderType: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ]
})

// 是否显示用户选择框
const showUserSelect = computed(() => {
  return currentPermission.userType === 'user'
})

// 根据value获取name的通用方法
const getName = (options, value, valueKey = 'value', labelKey = 'label') => {
  const item = options.find(item => item[valueKey] === value)
  return item ? item[labelKey] : value
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取工单类型列表
    const workOrderTypeRes = await getWorkOrderTypeList()
    workOrderTypeOptions.value = workOrderTypeRes.data

    // 获取用户类型列表
    const userTypeRes = await getUserTypeList()
    userTypeOptions.value = userTypeRes.data

    // 获取用户列表
    const userListRes = await getUserList()
    userListOptions.value = userListRes.data

    // 获取权限列表
    await fetchPermissionList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    loading.value = true
    const res = await getWorkOrderPermissionList(queryParams)
    permissionList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 处理工单类型变化
const handleWorkOrderTypeChange = () => {
  queryParams.pageNum = 1
  fetchPermissionList()
}

// 处理用户类型变化
const handleUserTypeChange = () => {
  queryParams.pageNum = 1
  fetchPermissionList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchPermissionList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchPermissionList()
}

// 显示新增对话框
const showAddDialog = () => {
  editDialogTitle.value = '新增权限'
  resetCurrentPermission()
  editDialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  editDialogTitle.value = '编辑权限'
  Object.assign(currentPermission, row)
  editDialogVisible.value = true
}

// 处理用户类型选择
const handleUserTypeSelect = (value) => {
  if (value !== 'user') {
    currentPermission.userId = ''
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.applicationId).join(',');
}
// 重置当前权限
const resetCurrentPermission = () => {
  currentPermission.permissionId = ''
  currentPermission.workOrderType = queryParams.workOrderType || ''
  currentPermission.userType = queryParams.userType || ''
  currentPermission.userId = ''
  currentPermission.userName = ''
  currentPermission.viewPermission = 0
  currentPermission.createPermission = 0
  currentPermission.editPermission = 0
  currentPermission.deletePermission = 0
  currentPermission.assignPermission = 0
}

// 确认编辑/新增
const confirmEdit = async () => {
  try {
    await formRef.value.validate()

    // if (currentPermission.userType === 'user') {
    //   const user = userListOptions.value.find(item => item.id === currentPermission.userId)
    //   if (user) {
    //     currentPermission.userName = user.name
    //   }
    // } else {
    //   currentPermission.userId = ''
    //   currentPermission.userName = ''
    // }
    console.log(currentPermission);
    
    if (currentPermission.permissionId) {
      // 更新权限
      await updateWorkOrderPermission(currentPermission)
      ElMessage.success('修改权限成功')
    } else {
      // 新增权限
      await addWorkOrderPermission(currentPermission)
      ElMessage.success('新增权限成功')
    }

    editDialogVisible.value = false
    fetchPermissionList()
  } catch (error) {
    console.error('保存权限失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 显示批量设置对话框
const showBatchDialog = () => {
  batchForm.workOrderType = queryParams.workOrderType
  batchForm.userType = queryParams.userType
  batchDialogVisible.value = true
}

// 确认批量设置
const confirmBatchSet = async () => {
  try {
    await batchSetWorkOrderPermission(batchForm)
    ElMessage.success('批量设置成功')
    batchDialogVisible.value = false
    fetchPermissionList()
  } catch (error) {
    console.error('批量设置失败:', error)
    ElMessage.error('批量设置失败')
  }
}

// 处理保存单条权限
const handleSave = async (row) => {
  try {
    if (row.permissionId) {
      // 更新权限
      await updateWorkOrderPermission(row)
      ElMessage.success('修改权限成功')
    } else {
      // 新增权限
      await addWorkOrderPermission(row)
      ElMessage.success('新增权限成功')
    }
    fetchPermissionList()
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

// 处理删除权限
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该权限配置吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWorkOrderPermission(row.permissionId)
      ElMessage.success('删除成功')
      fetchPermissionList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  gap: 15px;
}

.order-type-select {
  width: 250px;
}

.user-type-select {
  width: 200px;
}

.permission-table {
  width: 100%;
  margin-bottom: 20px;
}

.batch-actions {
  text-align: right;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容居中对齐 */
:deep(.el-table th),
:deep(.el-table td) {
  text-align: center !important;
}

/* 表格单元格内边距 */
:deep(.el-table .cell) {
  padding: 8px;
}

/* 复选框样式 */
:deep(.el-checkbox) {
  margin-right: 0;
}
</style>